<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>产品信息</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>产品信息</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<input class="layui-input" name="keyword01" id="keyword01" placeholder="请输入车型" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td> 
					<td>
						<input class="layui-input" name="keyword02" id="keyword02" placeholder="请输入车种" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
	</script>
	<script type="text/html" id="productAddRowToolbar">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="proDel"><i class="layui-icon layui-icon-delete"></i>删除</a>
	</script>

	<!-- 导入框 -->
	<div id="importDiv" hidden="hidden">
		<form class="layui-form" id="uploadform">
			<div style="margin: 20px 0 20px 140px;">
				<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
			</div>
		</form>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
		<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
	</div>
	<!-- 添加/修改框 -->
	<div id="addDivID" hidden="hidden">
		<form class="layui-form" id="addFormID">
			 <!-- id -->
			<input type="hidden" id="id" name="id">
			<label class="layui-form-label">车种</label></td>
			<input class="layui-input" id="productName" name="productName" style="width: 300px" lay-verify="required" placeholder="请输入车种">
			<span class="xing"></span>
			<br>
			<label class="layui-form-label">车型</label></td>
			<input class="layui-input" id="productNumber" name="productNumber" lay-verify="only" style="width: 300px; margin-top:15px" placeholder="请输入车型">
			<span class="xing"></span> 
			<br>
			<label class="layui-form-label">内饰</label></td>
			<input class="layui-input" id="inner" name="inner" style="width: 300px" placeholder="请输入内饰">
			<br>
			<label class="layui-form-label">外饰</label></td>
			<input class="layui-input" id="out" name="out" style="width: 300px; margin-top:15px" placeholder="请输入外饰">
			<br>
			<label class="layui-form-label">备注</label></td>
			<input class="layui-input" id="remark" name="remark" style="width: 300px; margin-top:15px" placeholder="请输入备注">
			<br>
			<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:140px;">立即提交</button>
			&emsp;&emsp;&emsp;&emsp;
			<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button></td>
			<!-- <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
		</form>
    </div>

	<script type="text/javascript">
		$(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
			e.stopPropagation();
		});

        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $.trim($("#keyword01").val());
	                var keyword02 = $.trim($("#keyword02").val());
					table.reload('contenttable',{
						method:'get',
						where:{
							productNumber:keyword01
	                        , 
	                        productName:keyword02
						}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/product/list.do'
				,toolbar: '#toolbar'
				,title: 'machineList'
				,id :'contenttable'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,request: {   //如果无需自定义请求参数，可不加该参数
	                pageName: 'page' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
	            }
	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
	                countName: 'total' //规定数据总数的字段名称，默认：count
	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
	            }
				,cols: [
		                [{
		                    type: 'checkbox',
		                    fixed: 'left'
		                }, {
		                	field:'id',
		                	title:'序号', 
		                	sort: true,
		                	width: 60,
		                	type:'numbers',
		                	align:'center'
		                } , {
		                	field: 'productName',
		                    title: '车种',
		                    align:'center',
		                } , {
		                   
		                    field: 'productNumber',
		                    title: '车型',
		                    align:'center' 
		                }, {
		                	field: 'inner',
		                    title: '内饰',
		                    align:'center',
		                } , {
		                   
		                    field: 'out',
		                    title: '外饰',
		                    align:'center' 
		                } , {
		                   
		                    field: 'remark',
		                    title: '备注',
		                    align:'center' 
		                }, {
		                    fixed: 'right',
		                    title:'操作',
		                    toolbar: '#rowToolbar',
		                    align:'center',
		                    unresize: true,
		                    width: 150 
		                }
		                ]
		               ]
				,page: true
				,done : function(){
	                $('th').css({
	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                    //'font-size': 10,
	                })
	            }
			});
			
			
            $('#downloadFile').click(function(){
                layer.confirm('确认下载模板吗？', function(index){
                    var url = "${pageContext.request.contextPath }/excel/excelTemplate.do?title=工厂信息"
                    window.location.href = url;
                    layer.close(index);
                });
            });

			
			//监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				//单个删除
				if(obj.event === 'del'){
				  layer.confirm('确定删除吗？', function(index){
					var id = obj.data.id;
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/product/delete.do',
						data:{ "ids" : id },
						success:function(data){
							if(data > 0){
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
							}else{
								toastr.warning("删除失败！");
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					});
					layer.close(index);
				  });
				} else if(obj.event === 'edit'){
					layer.open({
					  type: 1 							//Page层类型
					  ,area: ['500px', '550px'] //宽  高
					  ,title: '编辑'
					  ,shade: 0.6 						//遮罩透明度
					  ,maxmin: true 					//允许全屏最小化
					  ,anim: 1 							//0-6的动画形式，-1不开启
					  ,content: $('#addDivID')
                      ,end: function () {
                          var formDiv = document.getElementById('addDivID');
                          formDiv.style.display = '';
                      }
                      ,success: function(){
                    	  $("#id").val(data.id)
                    	  $("#productNumber").val(data.productNumber)
                    	  $("#productName").val(data.productName)
                    	  $("#inner").val(data.inner)
                    	  $("#out").val(data.out)
                    	  $("#remark").val(data.remark)
                          form.render();
                      }
					});
				}
			});

            /**
             * 通用表单提交(AJAX方式)（导入）
             */
            form.on('submit(uplodeform)', function (data) {
            	var index = layer.load(1, {
            	    shade: [0.1,'#000'] //0.1透明度的背景
            	});
                var formData = new FormData($("#uploadform")[0]);
                $.ajax({
                    url: '${pageContext.request.contextPath}/product/uplodeFile.do' ,
                    type: 'post',
                    data: formData,
                    dataType:'JSON',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data == 1) {
                            toastr.success("文件导入成功！");
                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                window.location.reload();
                                $("#reset").click();
                            },1000);
                        }else if(data == -1){
                            toastr.warning("导入的数据不符合导入条件！");
                        }else{
                            toastr.warning("文件格式异常，文件导入失败！");
                        }
                    },
                    error: function (data) {
                        toastr.error("文件格式异常，文件导入失败！");
                    }
                })
                layer.close(index);
                return false;
            });

			
			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				var index = layer.load(1, {
	        	    shade: [0.1,'#000'] //0.1透明度的背景
	        	});
				
				var formData = $("#addFormID").serialize();
				var url = '${pageContext.request.contextPath}/product/insert.do';
				var title = "新增";
				var id = $.trim($("#id").val());
				if(id != null && id != "" && id != 'undefined'){
					url = '${pageContext.request.contextPath}/product/update.do';
					title = "修改";
				} 
				$.ajax({
					url : url,
					data: formData,
					cache : false,
					type : "post",
					success: function (data) {
	                    if (data > 0) {
	                        toastr.success(title+'成功');
	                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                            window.location.reload();
	                            $("#reset").click();
	                        },1000);
	                    } else {
	                        toastr.error(title+'失败，该名称已存在，不能重复');
	                    }
	                },
				});
				layer.close(index);
				return false;
			});

			

			/**
	         * 表单校验
	         */
	        form.verify({
	            //value：表单的值、item：表单的DOM对象
	            required: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }
	            },
	            //value：表单的值、item：表单的DOM对象
	            only: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }else{
	                    var flg = false;
	                    var number = $.trim($("#productNumber").val());
	                	if(number == "" || number == null){
	                		flg  = true;
	                	}else{
		                    $.ajax({
		                        type:'post',
		                        data:"productNumber="+number,
		                        url:'${pageContext.request.contextPath}/product/queryAllByMution.do',
		                        dataType: 'JSON',
		                        async: false,
		                        success:function (data) {
		                            if(data.length == 0){
		                                flg  = true;
		                            }else if(data.length == 1){
		                                var ma = $.trim($("#id").val());
		                                if (ma == data[0].id) {
		                                    flg  = true;
		                                }else{
		                                    flg = false;
		                                }
		                            }else{
		                                flg = false;
		                            }
	
		                        }
		                    });
	                	}
	                    if(!flg){
	                        return '车型不能重复';
	                    }
	                }
	            }
	        });
			
			//增加
            $("#add").click(function(){
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['500px', '550px'] //宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                    	$("#id").val("")
                  	    $("#productNumber").val("")
                  	    $("#productName").val("")
                  	    $("#inner").val("")
                  	    $("#out").val("")
                  	    $("#remark").val("")
                        form.render();
                    }
                });
			});

          //批量删除
			$("#dels").click(function(){
				var checkStatus = table.checkStatus('contenttable')
	      		var data = checkStatus.data;
	            if(data.length==0){
	                toastr.warning("请至少选择一条记录！");
	            }else{
	                var ids = "";
	                for(var i=0;i<data.length;i++){
	                    if(i == 0 || i == "0"){
	                        ids += data[i].id
	                    }else{
	                        ids += "," + data[i].id;
	                    }
	                }
	                layer.confirm('确定删除吗？', function(index){
	                    $.ajax({
	                        type:'post',
	                        url:'${pageContext.request.contextPath }/product/delete.do',
	                        data:{"ids":ids},
	                        success:function(data){
	                            if(data>0){
	                                toastr.success("删除成功！");
	                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                                    //关闭模态框
	                                    // 父页面刷新
	                                    window.location.reload();
	                                },2000);
	                            }else{
	                                toastr.warning("删除失败！");
	                            }
	                        }

	                    })
	                    layer.closeAll();
	                });
	            }
			});
		});
		
		//导入
		function doExportall(){
			//var keyword01 = $.trim($("#keyword01").val());
            var keyword02 = $.trim($("#keyword02").val());
			var canshu =  "?"
				+"title"+"="+"工厂信息"
				//+"&"+"fnumber"+"="+keyword01
				+"&"+"fname"+"="+keyword02;
			layer.confirm('确认导出信息吗？', function(index){
                var url = "${pageContext.request.contextPath }/product/doExportall.do"+canshu;
                window.location.href=url;
                layer.close(index);
			});
		}
		function uploadExcel(){
			layer.open({
                type: 1 		//Page层类型
                ,area: ['400px', '200px'] //宽  高
                ,title: '导入'
                ,shade: 0.6 	//遮罩透明度
                ,maxmin: true //允许全屏最小化
                ,anim: 1 		//0-6的动画形式，-1不开启
                ,content: $('#importDiv')
                ,end: function () {
                    var formDiv = document.getElementById('importDiv');
                    formDiv.style.display = '';
                }
				,success: function(){
					$("#uploadform")[0].reset();
	            }
            });
		}
		
		toastrStyle()
	</script>
</body>
</html>